package com.andon.microcellsimulator.common.util;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

/**
 * Log工具类
 * tag自动产生，格式: TAG:className.methodName(Line:lineNumber)
 * DEFAULT_TAG为空时只输出：className.methodName(Line:lineNumber)
 */
public class LogUtil {
    // 自定义Tag的前缀
    public static String DEFAULT_TAG = "";
    private static final String LINE_BREAK = "\r\n";

    // 容许打印日志的类型，默认是true，设置为false则不打印
    public static boolean allowV = true;
    public static boolean allowD = true;
    public static boolean allowI = true;
    public static boolean allowW = true;
    public static boolean allowE = true;

    private static String PATH_LOG_INFO;

    private static final ThreadLocal<ReusableFormatter> thread_local_formatter = new ThreadLocal<ReusableFormatter>() {
        protected ReusableFormatter initialValue() {
            return new ReusableFormatter();
        }
    };

    public static void v(String content) {
        v(generateTag(getCallerStackTraceElement(4)), content, false);
    }

    public static void v(String tag, String content, boolean isSaveLog) {
        if (!allowV)
            return;

        Log.v(getTag(tag), content);

        if (isSaveLog) {
            point(PATH_LOG_INFO, getTag(tag), content);
        }
    }

    public static void d(String content) {
        d(generateTag(getCallerStackTraceElement(4)), content, false);
    }

    public static void d(String tag, String content, boolean isSaveLog) {
        if (!allowD) {
            return;
        }

        Log.d(getTag(tag), content);

        if (isSaveLog) {
            point(PATH_LOG_INFO, getTag(tag), content);
        }
    }

    public static void i(String content) {
        i(generateTag(getCallerStackTraceElement(4)), content, false);
    }

    public static void i(String tag, String content, boolean isSaveLog) {
        if (!allowI) {
            return;
        }

        Log.i(getTag(tag), content);

        if (isSaveLog) {
            point(PATH_LOG_INFO, getTag(tag), content);
        }
    }

    public static void w(String content) {
        w(generateTag(getCallerStackTraceElement(4)), content, false);
    }

    public static void w(String tag, String content, boolean isSaveLog) {
        if (!allowW) {
            return;
        }

        Log.w(getTag(tag), content);

        if (isSaveLog) {
            point(PATH_LOG_INFO, getTag(tag), content);
        }
    }

    public static void e(String content) {
        e(generateTag(getCallerStackTraceElement(4)), content, null, false);
    }

    public static void e(String content, Throwable tr) {
        e(generateTag(getCallerStackTraceElement(4)), content, tr, false);
    }

    public static void e(String tag, String content, Throwable tr, boolean isSaveLog) {
        if (!allowE)
            return;

        Log.e(getTag(tag), content, tr);

        String msg = getThrowable(tr, content);
        if (isSaveLog) {
            point(PATH_LOG_INFO, getTag(tag), msg);
        }
    }

    private static String getTag(String tag) {
        return tag == null ? generateTag(getCallerStackTraceElement(5)) : tag;
    }

    private static StackTraceElement getCallerStackTraceElement(int deep) {
        return Thread.currentThread().getStackTrace()[deep];
    }

    private static void point(String path, String tag, String msg) {
        if (isSDAva()) {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("",
                    Locale.SIMPLIFIED_CHINESE);
            dateFormat.applyPattern("yyyy");
            path = path + dateFormat.format(date) + "/";
            dateFormat.applyPattern("MM");
            path += dateFormat.format(date) + "/";
            dateFormat.applyPattern("dd");
            path += dateFormat.format(date) + ".log";
            dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]");
            String time = dateFormat.format(date);
            File file = new File(path);
            if (!file.exists())
                createDipPath(path);
            BufferedWriter out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(file, true)));
                out.write(time + " " + tag + " " + msg + "\r\n");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据文件路径 递归创建文件
     *
     * @param file
     */
    public static void createDipPath(String file) {
        String parentFile = file.substring(0, file.lastIndexOf("/"));
        File file1 = new File(file);
        File parent = new File(parentFile);
        if (!file1.exists()) {
            parent.mkdirs();
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String format(String msg, Object... args) {
        ReusableFormatter formatter = thread_local_formatter.get();
        return formatter.format(msg, args);
    }

    public static boolean isSDAva() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || Environment.getExternalStorageDirectory().exists()) {
            return true;
        } else {
            return false;
        }
    }

    private static String generateTag(StackTraceElement caller) {
        String tag = "(%s:%d).%s"; // 占位符
        tag = String.format(tag, caller.getFileName(), caller.getLineNumber(), caller.getMethodName()); // 替换
        tag = (DEFAULT_TAG == null || "".equalsIgnoreCase(DEFAULT_TAG)) ? tag : DEFAULT_TAG + ":"
                + tag;
        return tag;
    }

    private static String getThrowable(Throwable throwable, String msg) {
        /* 打印异常 */
        StringBuilder sb = new StringBuilder();
        if (msg != null) {
            sb.append(msg);
        }
        if (throwable != null) {
            sb.append(LINE_BREAK);
            StringWriter stringWriter = new StringWriter();
            throwable.printStackTrace(new PrintWriter(stringWriter));
            sb.append(stringWriter.toString());
        }
        return sb.toString();
    }

    /**
     * A little trick to reuse a formatter in the same thread
     */
    private static class ReusableFormatter {

        private Formatter formatter;

        private StringBuilder builder;

        public ReusableFormatter() {
            builder = new StringBuilder();
            formatter = new Formatter(builder);
        }

        public String format(String msg, Object... args) {
            formatter.format(msg, args);
            String s = builder.toString();
            builder.setLength(0);
            return s;
        }

    }
}
